package com.dome.mvp.base;

import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import com.dome.mvp.utils.ActivityManageUtils;
import com.jaeger.library.StatusBarUtil;

/**
 * Time: 6/1/2021 9:24
 * Author: TAO
 * Description:
 */
public abstract class BaseActivity<V extends IBaseView, P extends BasePresenter<V>, VDB extends ViewDataBinding> extends AppCompatActivity
        implements IBaseView {
    /**
     * 逻辑处理实例 {@link #createPresenter} 创建实例对象
     */
    protected P presenter;
    /**
     * 视图实例 {@link #getBind()} 获取实例对象
     */
    private VDB bind;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManageUtils.getInstance().pushActivity(this);

        // 是否使用 dataBinding
        if (isBinding()) {
            bind = DataBindingUtil.setContentView(this, getLayoutRes());
            bind.setLifecycleOwner(this);
        } else {
            setContentView(getLayoutRes());
        }
        // 是否隐藏状态栏
        if (isTranslucent()) {
            StatusBarUtil.setTranslucentForImageView(this, 0, null);
            StatusBarUtil.setLightMode(this);
        }

        // 创建实例对象
        presenter = createPresenter();
        if (presenter == null) return;
        bind.setVariable(variableId(), presenter);
        // 添加视图层到逻辑处理
        presenter.attach((V) this);
        // presenter 添加生命周期监听
        getLifecycle().addObserver(presenter);
        // 注册第三方sdk
        registerSdk();
        // 初始化
        init();
    }

    @Nullable
    protected abstract P createPresenter();


    public VDB getBind() {
        return bind;
    }

    @Override
    public void init() {

    }

    @Override
    public void registerSdk() {

    }

    @Override
    public void unRegisterSdk() {

    }

    @Override
    public void showError(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean isBinding() {
        return true;
    }

    @Override
    public boolean isTranslucent() {
        return true;
    }

    @Override
    protected void onDestroy() {
        ActivityManageUtils.getInstance().pop();
        if (presenter != null) {
            getLifecycle().removeObserver(presenter);
            presenter.detach();
            presenter = null;
        }
        if (bind != null) {
            bind.unbind();
            bind = null;
        }
        unRegisterSdk();
        super.onDestroy();
    }

}
